package com.yuerenjf.yuerenjinfu.fragment;

import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.CommonUtils;
import com.yuerenjf.yuerenjinfu.utils.CustomImageSpan;
import com.yuerenjf.yuerenjinfu.utils.MessageTimer;
import com.yuerenjf.yuerenjinfu.utils.SMSContent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/21 0021.
 */

public class RegisterFragment extends BaseFragment {
    private TextView tv_register_login;
    private TextView tv_register_complete;
    private TextView tv_register_code;
    private EditText et_register_username;
    private EditText et_register_pwd;
    private EditText et_register_code;
    private EditText et_pwd_again;
    private SMSContent smsContent;
    private EditText et_register_invite;
    private EditText etPasswordAgainEdit;


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setmTitleTextView("注册");
        mainActivity.setLogoImageShow(false);

    }

    @Override
    public void prepareData() {

    }

    @Override
    public View prepareView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.activity_register, null);
        tv_register_login = (TextView) view.findViewById(R.id.tv_register_login);
        tv_register_complete = (TextView) view.findViewById(R.id.tv_register_complete);
        tv_register_code = (TextView) view.findViewById(R.id.tv_register_code);
        et_register_username = (EditText) view.findViewById(R.id.et_register_username);
        et_register_pwd = (EditText) view.findViewById(R.id.et_register_pwd);
        et_pwd_again = (EditText) view.findViewById(R.id.et_pwd_again);
        et_register_code = (EditText) view.findViewById(R.id.et_register_code);
        tv_register_agreement = (TextView) view.findViewById(R.id.tv_register_agreement);
        et_register_invite = (EditText) view.findViewById(R.id.et_register_invite);
//        etPasswordAgainEdit = (EditText) view.findViewById(R.id.et_register_pwd_again);
//        tv_register_agreement.setOnClickListener(mOnClickListener);
        tv_register_login.setOnClickListener(mOnClickListener);
        tv_register_complete.setOnClickListener(mOnClickListener);
        tv_register_code.setOnClickListener(mOnClickListener);


        initAgreeLayout(tv_register_agreement);

        smsContent = new SMSContent(new Handler(), getActivity(), et_register_code);
        getActivity().getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsContent);

        return view;
    }

    @Override
    public void onloadData(View view) {

    }

    @Override
    public void adapterScreen() {

    }


    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_register_login:
                    MainActivity mainActivity = (MainActivity) getActivity();
//                    while (mainActivity.getFm().getBackStackEntryCount() > 0) {
                    mainActivity.getFm().popBackStackImmediate();
//                    }

//                    startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                    break;
                case R.id.tv_register_code:
                    if (!CommonUtils.isMobileNO(et_register_username.getText().toString())) {
                        Toast.makeText(getActivity(), "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    sendCode(et_register_username.getText().toString());
                    break;
                case R.id.tv_register_complete:
                    if (!CommonUtils.isMobileNO(et_register_username.getText().toString())) {
                        Toast.makeText(getActivity(), "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (et_register_code.getText().toString().equals("")) {
                        Toast.makeText(getActivity(), "验证码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(et_register_pwd.getText().toString())) {
                        Toast.makeText(getActivity(), "密码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!CommonUtils.isPassword(et_register_pwd.getText().toString())) {
                            Toast.makeText(getActivity(), "请输入8-20位密码", Toast.LENGTH_SHORT).show();
                            return;
                    }
                    if (!etPasswordAgainEdit.getText().toString().equals(et_register_pwd.getText().toString())) {
                        Toast.makeText(getActivity(), "两次密码输入不一致", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (!isCheck) {
                        Toast.makeText(getActivity(), "注册用户需阅读并同意网站协议", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    register();
                    break;
                case R.id.ll_back:
//                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    private void sendCode(String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        Xutils.getInstance().post(getActivity(), Constants.URL_REGISTER_GET_CODE, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                Log.e("sendCode", result + "------");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    if (status == 200) {
                        Toast.makeText(getActivity(), "验证码发送成功", Toast.LENGTH_SHORT).show();
                        new MessageTimer(tv_register_code, 90000, 1000).start();

                    } else if (status == 400) {
                        String message = jsonObject.getString("message");
                        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(), "发送失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result) {

            }
            @Override
            public void onFinish() {

            }
        });


    }

    private void register() {

        Map<String, String> map = new HashMap<>();
        map.put("phone", et_register_username.getText().toString());
        map.put("password", et_register_pwd.getText().toString());
        map.put("captcha", et_register_code.getText().toString());
        map.put("pwd", etPasswordAgainEdit.getText().toString());
        map.put("invite_code", et_register_invite.getText().toString());
        Xutils.getInstance().post(getActivity(), Constants.URL_REGISTER, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                Log.e("sendCode", result + "------");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    String message = jsonObject.getString("message");
                    if (status == 200) {
                        Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
//                        finish();
                        MainActivity mainActivity = (MainActivity) getActivity();
                        mainActivity.getFm().popBackStackImmediate();
                    } else if (status == 300) {
                        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(), "注册失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    private TextView tv_register_agreement;
    private boolean isCheck = true;


    private void initAgreeLayout(TextView view) {
        Html.ImageGetter imageGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                int id = Integer.parseInt(source);

                //根据id从资源文件中获取图片对象
                Drawable d = getResources().getDrawable(id);
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                return d;
            }
        };
//        Spanned str=Html.fromHtml("<img src=\""+R.drawable.ssdk_oks_auth_follow_cb_chd+"\"> 我已阅读并同意"
//                , imageGetter, null);
        SpannableString spanableInfo = new SpannableString(" 我已阅读并同意");
        CustomImageSpan imageSpan = new CustomImageSpan(getActivity(), R.drawable.icon_register_selected, 2);
        spanableInfo.setSpan(imageSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanableInfo.setSpan(new Clickable(imageClickListener),
                0, 1, //设置需要监听的字符串位置
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        view.append(spanableInfo);

        SpannableString spanableInfo2 = new SpannableString("《中普金服注册服务协议》《出借资讯管理服务协议》");
        spanableInfo2.setSpan(new Clickable(click),
                0, 12, //设置需要监听的字符串位置
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanableInfo2.setSpan(new Clickable(clickListener), 12,
                24,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        view.append(spanableInfo2);
        view.setMovementMethod(LinkMovementMethod.getInstance());
        view.setHighlightColor(getResources().getColor(android.R.color.transparent));
    }

    private View.OnClickListener click = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            LogUtil.i("中普金服注册服务");
        }
    };
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtil.i("出借资讯管理服务");
        }
    };
    private View.OnClickListener imageClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtil.i("点击图片");
        }
    };


    class Clickable extends ClickableSpan {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener l) {
            mListener = l;
        }

        /**
         * 重写父类点击事件
         */
        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);// 设置文字下划线不显示
            ds.setColor(getResources().getColor(R.color.dark_title));// 设置字体颜色
            ds.clearShadowLayer();
        }
    }
}
